package com.zsxb.crm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zsxb.crm.dto.TransferPageDTO;
import com.zsxb.crm.mapper.BusinessMapper;
import com.zsxb.crm.mapper.ClueMapper;
import com.zsxb.crm.mapper.TransferMapper;
import com.zsxb.crm.mapper.UserMapper;
import com.zsxb.crm.pojo.Transfer;
import com.zsxb.crm.pojo.User;
import com.zsxb.crm.result.PageResult;
import com.zsxb.crm.service.TransferService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class TransferServiceImpl implements TransferService {

    @Autowired
    private TransferMapper transferMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private BusinessMapper businessMapper;

    /**
     * 转派分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult pageQuery(TransferPageDTO dto) {
        log.info("转派分页查询参数：{}",dto);
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        Page<Transfer> page = transferMapper.pageQuery(dto);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRows(page.getResult());
        return pageResult;
    }

    //插入数据，添加用户后触发
    @Override
    public  void addBusiness(User user) {
        Integer clueNum = clueMapper.getClueNum(user);
        Integer businessNum = businessMapper.getBusinessNum(user);
        Transfer transfer = new Transfer();
        transfer.setUserId(user.getId());
        transfer.setUserName(user.getUserName());
        transfer.setPhonenumber(user.getPhonenumber());
        transfer.setClueNum(clueNum);
        transfer.setBusinessNum(businessNum);
        transferMapper.insert(transfer);
    }

    @Override
    public void assignment(Long cOrB, Long isUserId, Long outUserId) {
        if (cOrB == 0){
            clueMapper.updateByUserId(isUserId,outUserId);
        }else{
            businessMapper.updateByUserId(isUserId,outUserId);
        }
        updateDate(isUserId);
        updateDate(outUserId);
    }

    public void updateDate (Long userId){
        Integer clueNum = clueMapper.getClueNum(userId);
        Integer businessNum = businessMapper.getBusinessNum(userId);
        transferMapper.updateDate(userId,clueNum,businessNum);
    }

}
